package com.wei.lawyer.ui.activity;

import android.graphics.Color;
import android.os.Bundle;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wei.lawyer.App;
import com.wei.lawyer.R;
import com.wei.lawyer.model.LawHistoryBean;
import com.wei.lawyer.model.LawSearchBean;
import com.wei.lawyer.net.BasePresenter;
import com.wei.lawyer.sql.LawHistoryBeanDao;
import com.wei.lawyer.ui.adapter.BaseDelegateAdapter;
import com.wei.lawyer.ui.adapter.BaseViewHolder;
import com.wei.lawyer.utils.StatusBarUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 作者：赵若位
 * 时间：2018/11/6 17:46
 * 邮箱：1070138445@qq.com
 * 功能：
 */
public class LawSearchActivity extends BaseActivity
{
    @Bind(R.id.mDrawer)
    DrawerLayout mDrawer;
    @Bind(R.id.et_law)
    EditText mEtLaw;
    @Bind(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @Bind(R.id.refresh)
    SmartRefreshLayout mRefresh;
    @Bind(R.id.tv_title)
    TextView mTvTitle;

    @Bind(R.id.tv_related)
    TextView mTvRelated;
    @Bind(R.id.tv_time)
    TextView mTvTime;
    @Bind(R.id.tv_condition)
    TextView mTvCondition;

    /*总数据适配器*/
    private DelegateAdapter mAdapter;
    /*历史纪录适配器*/
    private BaseDelegateAdapter mTitleAdapter, mHistoryAdapter, mClearAdapter;
    /*搜索记录适配器*/
    private BaseDelegateAdapter mSearchAdapter;


    @Override
    protected int getLayoutResource()
    {
        return R.layout.activity_law_search;
    }

    @Override
    protected void setStatusBarColor()
    {

    }

    @Override
    protected BasePresenter createPresenter()
    {
        return null;
    }


    @Override
    protected void initView(Bundle savedInstanceState)
    {
        super.initView(savedInstanceState);
        StatusBarUtils.setColorNoTranslucentForDrawerLayout(this, mDrawer, Color.WHITE);
        setLeftBack();
        /*关闭DrawLayout手势滑动*/
        mDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        /*设置EditText监听*/
        mEtLaw.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {

            }

            @Override
            public void afterTextChanged(Editable s)
            {
                String law = mEtLaw.getText().toString();
                if (TextUtils.isEmpty(law))
                {
                    setHistoryList();
                }
            }
        });

        VirtualLayoutManager manager = new VirtualLayoutManager(this);
        manager.setInitialPrefetchItemCount(5);
        mRecyclerView.setLayoutManager(manager);
        //关闭动效提升效率
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        //Item高度固定，避免浪费资源
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setItemViewCacheSize(5);

        //历史纪录
        mAdapter = new DelegateAdapter(manager, false);
        mRecyclerView.setAdapter(mAdapter);

        initAdapter();
    }

    /*初始化适配器*/
    private void initAdapter()
    {
        //标题
        mTitleAdapter = new BaseDelegateAdapter<String>(this, R.layout.item_law_search_history)
        {
            @Override
            public void convert(BaseViewHolder holder, int position, String s)
            {
                holder.setText(s, R.id.item_title)
                        .setTextColor(R.id.item_title, Color.parseColor("#afafaf"));
            }
        };
        mAdapter.addAdapter(mTitleAdapter);

        //搜索记录
        mHistoryAdapter = new BaseDelegateAdapter<LawHistoryBean>(this, R.layout.item_law_search_history)
        {
            @Override
            public void convert(BaseViewHolder holder, int position, final LawHistoryBean data)
            {
                holder.setText(data.getDescript(), R.id.item_title)
                        .itemView.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        setSearchList(data.getDescript());
                    }
                });
            }
        };
        mAdapter.addAdapter(mHistoryAdapter);

        //清除历史纪录
        mClearAdapter = new BaseDelegateAdapter<String>(this, R.layout.layout_law_search_history_clear)
        {
            @Override
            public void convert(BaseViewHolder holder, int position, String s)
            {
                holder.setOnClickListener(R.id.tv_clear, new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        showMsgDialog(getString(R.string.dialog_law_search_clear), new View.OnClickListener()
                        {
                            @Override
                            public void onClick(View v)
                            {
                                App.mSession.getLawHistoryBeanDao().deleteAll();
                                setHistoryList();
                                disMsgDialog();
                            }
                        });
                    }
                });
            }
        };
        mAdapter.addAdapter(mClearAdapter);

        //搜索
        mSearchAdapter = new BaseDelegateAdapter<LawSearchBean>(this, R.layout.item_law_search)
        {
            @Override
            public void convert(BaseViewHolder holder, int position, LawSearchBean data)
            {
                holder.setText(data.getTitle(), R.id.item_title)
                        .setText(data.getAuthor(), R.id.item_author)
                        .setText(data.getType(), R.id.item_type)
                        .setText(data.getDescript(), R.id.item_descript);
            }
        };
        mAdapter.addAdapter(mSearchAdapter);
    }


    /*设置刷新监听*/
    private void setRefreshListener()
    {
        mRefresh.setEnableRefresh(true);
        mRefresh.setEnableLoadMore(true);
    }

    /*清除刷新监听*/
    private void clearRefreshListener()
    {
        mRefresh.setEnableRefresh(false);
        mRefresh.setEnableLoadMore(false);
    }


    @Override
    protected void initData()
    {
        super.initData();
        setHistoryList();
    }

    /*查询本地搜索历史纪录*/
    private List<LawHistoryBean> getHistoryList()
    {
        LawHistoryBeanDao dao = App.mSession.getLawHistoryBeanDao();
        if (dao == null) return null;
        List<LawHistoryBean> list = dao.queryBuilder().orderDesc(LawHistoryBeanDao.Properties.MTime).list();
        if (list == null || list.isEmpty())
        {
            mClearAdapter.clearData();
        } else
        {
            mClearAdapter.setData("");
        }
        return list;
    }

    /*设置历史记录数据*/
    private void setHistoryList()
    {
        mTitleAdapter.setData(getString(R.string.tv_law_history));
        mHistoryAdapter.setData(getHistoryList());
        mSearchAdapter.clearData();
        findViewById(R.id.layout_condition).setVisibility(View.GONE);
        /*关闭下拉刷新和上啦加载更多*/
        clearRefreshListener();
    }


    /*设置搜索记录数据*/
    private void setSearchList(String descript)
    {
        if (TextUtils.isEmpty(descript)) return;
        findViewById(R.id.layout_condition).setVisibility(View.VISIBLE);
        setCondition(0);
        mTitleAdapter.clearData();
        mHistoryAdapter.clearData();
        mClearAdapter.clearData();

        List<LawSearchBean> list = new ArrayList<>();
        for (int i = 0; i < 20; i++)
        {
            list.add(new LawSearchBean(descript));
        }
        mSearchAdapter.setData(list);
        /*打开刷新监听*/
        setRefreshListener();
    }

    /*设置条件查询的UI和逻辑*/
    private void setCondition(int position)
    {
        mTvRelated.setTextColor(getResources().getColor(R.color.textTitle));
        mTvTime.setTextColor(getResources().getColor(R.color.textTitle));
        switch (position)
        {
            case 0:
                mTvRelated.setTextColor(getResources().getColor(R.color.toast));
                break;
            case 1:
                mTvTime.setTextColor(getResources().getColor(R.color.toast));
                break;
            default:
                break;
        }
    }

    @OnClick({R.id.tv_search, R.id.tv_related, R.id.tv_time, R.id.tv_condition})
    public void onViewClicked(View view)
    {
        switch (view.getId())
        {
            case R.id.tv_search://搜索
                if (isFastDoubleClick()) return;
                String law = mEtLaw.getText().toString();
                if (TextUtils.isEmpty(law))
                {
                    alert(getString(R.string.et_enter_key));
                    return;
                }
                setSearchList(law);
                //添加搜索记录
                App.mSession.getLawHistoryBeanDao().insertOrReplaceInTx(new LawHistoryBean(law));
                break;
            case R.id.tv_related://相关性
                setCondition(0);
                break;
            case R.id.tv_time://发布日期:
                setCondition(1);
                break;
            case R.id.tv_condition://筛选
                mDrawer.openDrawer(Gravity.RIGHT);
                break;
        }
    }

}
